<template>
  <div style="border: 1px solid #ccc; z-index: 999999999999" v-if="isRender">
    <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig" :mode="mode" />
    <Editor style="height: 500px; overflow-y: hidden" :default-html="valueHtml" :default-content="valueJSon" :defaultConfig="editorConfig" :mode="mode" @onCreated="handleCreated" @onChange="handleChange" />
  </div>
</template>

<script lang="ts">
import { computed, defineComponent, unref, watch } from 'vue';
import { useRuleFormItem } from '@/hooks/component/use-form-item';
import '@wangeditor/editor/dist/css/style.css';
import { onBeforeUnmount, ref, shallowRef, onMounted } from 'vue';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import { isJSON } from 'class-validator';
export default defineComponent({
  name: 'WangEditor',
  //不将 attrs 的属性绑定到 html 标签上
  inheritAttrs: false,
  components: { Editor, Toolbar },
  props: {
    value: {
      type: [String, Array, Object] as any,
    },
    valueType: {
      type: String,
      default: 'html',
    },
    disabled: {
      type: Boolean,
      default: false,
    },
  },
  emits: ['change', 'update:value'],
  setup(props, { emit, attrs }) {
    const emitData = ref<any>();
    //表单值
    const [state] = useRuleFormItem(props, 'value', 'change', emitData);
    //组件渲染标记,当赋值完成后渲染组件
    const isRender = ref(false);
    //是否是新增模式
    const isAdd = ref(false);
    //
    const tag = ref(false);
    const isJson = ref(false);
    // 编辑器实例，必须用 shallowRef
    const editorRef = shallowRef();
    // 合并 props 和 attrs
    const bindProps: any = computed(() => Object.assign({}, props, attrs));
    // 内容 HTML
    const valueHtml: any = ref('<p></p>');
    const valueJSon: any = ref(<any>[]);

    onMounted(() => {
      console.info('33333333333333', props.value);
    });

    /**
     * 监听组件值
     */
    watch(
      () => props.value,
      (val, val1) => {
        console.info('props.value', props.value);
        console.info('val', val);
        console.info('val1', val1);
        //加入flag判断防止编辑时重复触发watch事件
        if (props.value && isRender.value == false) {
          initValue();
        } else {
          isAdd.value = true;
        }
      },
    );

    /**
     * 组件赋值
     */
    function initValue() {
      tag.value = false;
      let value = unref(props.value);
      if (isJSON(value)) {
        isJson.value = true;
        valueJSon.value = JSON.parse(value);
      } else {
        valueHtml.value = value;
      }
      isRender.value = true;
      //加入延迟防止初始化赋值时触发handleChange
      setTimeout(() => {
        tag.value = true;
      }, 100);
    }
    const toolbarConfig = {
      excludeKeys: ['emotion', 'insertLink', 'group-video', 'group-image', 'codeBlock'],
    };
    const editorConfig = { placeholder: '请输入内容...' };

    // 组件销毁时，也及时销毁编辑器
    onBeforeUnmount(() => {
      const editor = editorRef.value;
      if (editor == null) return;
      editor.destroy();
    });

    const handleCreated = (editor) => {
      //editor 实例
      editorRef.value = editor;
    };

    //内容修改事件
    function handleChange(editor) {
      if (tag.value == true) {
        console.info('handleChange', tag.value);
        if (isJson.value) {
          state.value = JSON.stringify(editor.children);
          emit('update:value', JSON.stringify(editor.children));
        } else {
          state.value = editor.getHtml();
          emit('update:value', editor.getHtml());
        }
      }
    }

    return {
      editorRef,
      valueHtml,
      mode: 'default', // 或 'simple'
      toolbarConfig,
      editorConfig,
      handleCreated,
      valueJSon,
      isAdd,
      isRender,
      bindProps,
      handleChange,
    };
  },
});
</script>

<style lang="less" scoped>
.full-screen-container {
  z-index: 1000000;
}
</style>